// member
package controllers_member

import (
	"encoding/json"
	"github.com/martini-contrib/render"
	"martini_template/componnet"
	"martini_template/form"
	"martini_template/models/common"
	"martini_template/models/member"
	"martini_template/models/mongo"
	"net/http"
	"strconv"
	"time"
)

type Member struct {
	LoginUser models_member.Member
}

func (c *Member) CheckAccessToken(req *http.Request, resJson componnet.ResponsJson, r render.Render, form form.MemberForm, atForm form.AccessTokenForm) {
		componnet.Alogger.Println("["+req.RemoteAddr+"]", "["+req.RequestURI+"]",form, atForm)
		if atForm.AccessToken == "" {
			resJson.SetState(componnet.CODE_ACCESS_TOKEN_ERR)
			r.JSON(200, resJson)
			return
		} else {
			var model models_member.Member
			var tokenMedel models_mongo.MemberToken
			res := tokenMedel.LoadByToken(atForm.AccessToken)
			if res {
				loadRes := models_common.LoadString(tokenMedel.MemberId,&model)
				if loadRes {
					c.LoginUser = model
				}else{
					resJson.SetState(componnet.CODE_ACCESS_TOKEN_ERR)
					r.JSON(200, resJson)
					return
				}
			} else {
				resJson.SetState(componnet.CODE_ACCESS_TOKEN_ERR)
				r.JSON(200, resJson)
				return
			}
		}
}

func (c *Member) Register(req *http.Request, resp componnet.ResponsJson, r render.Render, form form.MemberForm) {
	var model models_member.Member
	if form.Username == "" {
		resp.SetState(componnet.CODE_MEMBER_ERR_USERNAME)
		r.JSON(200, resp)
		return
	}
	if form.Password == "" {
		resp.SetState(componnet.CODE_MEMBER_ERR_PASSWORD)
		r.JSON(200, resp)
		return
	}
	checkUsername := models_common.LoadByAttr("username", form.Username, new(models_member.Member))
	if checkUsername {
		resp.SetState(componnet.CODE_MEMBER_ERR_USERNAME_EXIST)
		r.JSON(200, resp)
		return
	}
	checkTelphone := models_common.LoadByAttr("telphone", form.Telphone, new(models_member.Member))
	if checkTelphone {
		resp.SetState(componnet.CODE_MEMBER_ERR_TELPHONE_EXIST)
		r.JSON(200, resp)
		return
	}
	checkEmail := models_common.LoadByAttr("email", form.Email, new(models_member.Member))
	if checkEmail {
		resp.SetState(componnet.CODE_MEMBER_ERR_EMAIL_EXIT)
		r.JSON(200, resp)
		return
	}
	model.Username = form.Username
	password, derr := componnet.AesDecrypt(form.Password)
	if derr != nil {
		resp.SetState(componnet.CODE_MEMBER_ERR_PASSWORD)
		r.JSON(200, resp)
		return
	}
	model.Password = password
	model.Email = form.Email
	model.Nickname = form.Nickname
	model.Realname = form.Realname
	model.RegisterIp = req.RemoteAddr
	var covertErr error
	sexInt, covertErr := strconv.Atoi(form.Sex)
	if covertErr == nil {
		model.Sex = sexInt
	}
	model.Avatar = form.Avatar
	model.Telphone = form.Telphone
	model.RegisterTime = time.Now().Unix()
	if form.Birthday != "" {
		birthday, cerr := strconv.ParseInt(form.Birthday, 10, 64)
		if cerr != nil {
			resp.SetState(componnet.CODE_MEMBER_ERR_BIRTHDAY)
			r.JSON(200, resp)
			return
		}
		model.Birthday = birthday
	}
	res, _ := model.SaveMember()
	if res {
		//注册日志
		var logModel models_mongo.OpLog
		logModel.OpAction = "会员注册"
		content, jerr := json.Marshal(form)
		if jerr == nil {
			logModel.OpContent = string(content)
		}
		logModel.OperId = ""
		logModel.OpIP = req.RemoteAddr
		logModel.OpType = "会员模块"
		logModel.OpTime = time.Now().Unix()
		logModel.SaveLog()
		//日志结束
		resp.SetState(componnet.CODE_SUCC)
		r.JSON(200, resp)
		return
	} else {
		resp.SetState(componnet.CODE_FAIL)
		r.JSON(200, resp)
		return
	}
}
func (c *Member) Update(resJson componnet.ResponsJson, r render.Render, form form.MemberForm) {
	if form.Email !="" {
		c.LoginUser.Email = form.Email	
	}
	if form.Nickname !="" {
		c.LoginUser.Nickname = form.Nickname
	}
	if form.Realname !=""{
		c.LoginUser.Realname = form.Realname
	}
	if form.Sex != "" {
		var covertErr error
		sexInt, covertErr := strconv.Atoi(form.Sex)
		if covertErr == nil {
			c.LoginUser.Sex = sexInt
		}else{
			resJson.SetState(componnet.CODE_MEMBER_ERR_SEX)
			r.JSON(200,resJson)
			return	
		}
	}
	if form.Avatar != ""{
		c.LoginUser.Avatar = form.Avatar
	}
	if form.Telphone != ""{
		c.LoginUser.Telphone = form.Telphone
	}
	if form.Birthday != ""{
		birthday,berr := strconv.ParseInt(form.Birthday,10,64)
		if berr	!= nil{
			resJson.SetState(componnet.CODE_MEMBER_ERR_BIRTHDAY)
			r.JSON(200,resJson)
			return			
		}else{
			c.LoginUser.Birthday = birthday
		}
	}
	res, _ := c.LoginUser.SaveMember()
	if res {
		resJson.SetState(componnet.CODE_SUCC)
		r.JSON(200, resJson)
		return
	} else {
		resJson.SetState(componnet.CODE_FAIL)
		r.JSON(200, resJson)
		return
	}
}


func (controller Member) Login(req *http.Request, resJson componnet.ResponsJson, r render.Render, loginForm form.LoginForm) {
	if loginForm.Username == "" {
		resJson.SetState(componnet.CODE_MEMBER_ERR_USERNAME)
		r.JSON(200, resJson)
		return
	}
	if loginForm.Password == "" {
		resJson.SetState(componnet.CODE_MEMBER_ERR_PASSWORD)
		r.JSON(200, resJson)
		return
	}
	var model models_member.Member
	password, cerr := componnet.AesDecrypt(loginForm.Password)
	if cerr != nil {
		componnet.Elogger.Println(cerr)
		resJson.SetState(componnet.CODE_MEMBER_ERR_PASSWORD)
		r.JSON(200, resJson)
		return
	}
	res, resCode := model.Login(loginForm.Username, password)
	if res {
		//检查是否已登录
		var mtk models_mongo.MemberToken
		loadRes := mtk.Load(model.Id, loginForm.DeviceCode)
		if !loadRes {
			mtk.DeviceCode = loginForm.DeviceCode
			mtk.DeviceName = loginForm.DeviceName
			mtk.Ip = req.RemoteAddr
			mtk.MemberId = model.Id
			mtk.CreateToken()

		}
		model.AccessToken = mtk.AccessToken
		resJson.SetState(componnet.CODE_SUCC)
		resJson.SetDataStruct(model)
		r.JSON(200, resJson)
		//登录日志
		var logModel models_mongo.OpLog
		logModel.OpAction = "会员登录"
		content := "从设备[" + loginForm.DeviceName + "],设备ID为[" + loginForm.DeviceCode + "]登录"
		logModel.OpContent = string(content)
		logModel.OperId = model.Id
		logModel.OpIP = req.RemoteAddr
		logModel.OpType = "会员模块"
		logModel.OpTime = time.Now().Unix()
		logModel.SaveLog()
		return
	} else {
		resJson.SetState(resCode)
		r.JSON(200, resJson)
		return
	}
}

func (c *Member) Banding(req *http.Request,resJson componnet.ResponsJson, r render.Render, form form.MemberForm) {
	
}

func (c *Member) Info(resJson componnet.ResponsJson, r render.Render){
	resJson.SetDataStruct(c.LoginUser)
	resJson.SetState(componnet.CODE_SUCC)
	r.JSON(200,resJson)
}

func (c *Member) Password(req *http.Request,resJson componnet.ResponsJson, r render.Render, form form.MemberForm) {
	if form.Password != "" {
		password,cerr := componnet.AesDecrypt(form.Password)
		if cerr != nil{
			resJson.SetState(componnet.CODE_MEMBER_ERR_PASSWORD)
			r.JSON(200, resJson)
			return
		}
		enPassword := componnet.Md5String(password)
		c.LoginUser.Password = enPassword
		res,_ := c.LoginUser.SaveMember()
		if res {
			//修改密码日志
			var logModel models_mongo.OpLog
			logModel.OpAction = "会员修改密码"
			content, jerr := json.Marshal(form)
			if jerr == nil {
				logModel.OpContent = string(content)
			}
			logModel.OperId = c.LoginUser.Id
			logModel.OpIP = req.RemoteAddr
			logModel.OpType = "会员模块"
			logModel.OpTime = time.Now().Unix()
			logModel.SaveLog()
			//结束日志
			resJson.SetState(componnet.CODE_SUCC)
			r.JSON(200, resJson)
			return
		} else {
			resJson.SetState(componnet.CODE_FAIL)
			r.JSON(200, resJson)
			return
		}
	}else{
		resJson.SetState(componnet.CODE_MEMBER_ERR_PASSWORD)
		r.JSON(200, resJson)
		return
	}
}
